﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SiGeSIB.GUI.Common;
using SiGeSIB.Data.Security;
using SiGeSIB.Data.Common;
using SiGeSIB.Services;

namespace SiGeSIB.GUI.Security
{
#if DESIGN
	public partial class FEditUser : FormRedirector.FEditUser
#else
	public partial class FEditUser : FGenericEditor<User>
#endif
	{
        #region Constructors
        public FEditUser()
            : this(EFormState.View, -1)
        { }
        public FEditUser(EFormState initialState, int id)
            : base(initialState, id)
        {
            InitializeComponent();
            InitialState = initialState;
            _Id = id;

            if (initialState == EFormState.View)
            {
                this.Text = "Edição de usuário";
                _IdleMessage = "Visualize as informações do usuário";
            }
            else
            {
                this.Text = "Inserção de usuário";
                _IdleMessage = "Insira as informações do usuário.";
            }

            FieldsToLock = new List<object>()
			{ 
			    lblLogin,
			    lblEmail, 
			    lblName,
			    lblConfirmPassword,
			    lblPassword,
				txtName,
				txtLogin,
				txtEmail,
				txtPassword,
				txtConfirmPassword
			};

            _Controller.AddErrorLabel("InvalidName", new Control[] { lblName, txtName });
            _Controller.AddErrorLabel("InvalidLogin", new Control[] { lblLogin, txtLogin });
            _Controller.AddErrorLabel("InvalidPassword", new Control[] { lblPassword, txtPassword });
            _Controller.AddErrorLabel("PasswordMismatch", new Control[] { lblPassword, txtPassword, lblConfirmPassword, txtConfirmPassword });
        } 
        #endregion

		#region Properties
		protected override bool HasEditPermission
		{
			get
			{
				return
					Manager.Instance.LoggedUser.IsAdmin
					||
					(
						Manager.Instance.LoggedUser.Permissions
						&
						EPermissions.ManageUser
					) != EPermissions.None;
			}
		}
		#endregion

        #region Overridens
        public override bool ConflictsWith(ConflictableForm form)
        {
            bool conflicts = false;

            if (form.GetType() == this.GetType())
            {
                // Só conflita se for inserção ou se for edição do mesmo elemento
                FEditUser fEdit = form as FEditUser;

                if (fEdit.InitialState == this.InitialState)
                {
                    if (this.InitialState == EFormState.Edit)
                        conflicts = true;
                    else if (this._CurrentEntity != null && fEdit._CurrentEntity != null && this._CurrentEntity.Id == fEdit._CurrentEntity.Id)
                        conflicts = true;
                }
            }

            return conflicts;
        }

        #region Loading
        protected override User _LoadEntity(int id)
        {
            ISecurityServicesProvider secProv = _Manager.ServicesProvider.CreateSecurityServicesProvider();

            return secProv.GetUser(id);
        }

        protected override void _FillEntity(User entity)
        {
            if (entity != null)
            {
                txtName.Text = entity.Name;
                txtLogin.Text = entity.Login;
                txtEmail.Text = entity.Email;
                txtPassword.Text = entity.Password;
                txtConfirmPassword.Text = entity.Password;
            }
            else
            {
                txtName.Text = null;
                txtLogin.Text = null;
                txtEmail.Text = null;
                txtPassword.Text = null;
                txtConfirmPassword.Text = null;
            }
        } 
        #endregion

        #region Commit
        protected override User _BuildEntity()
        {
            User entity = new User(false);

            entity.Id = _Id;
            entity.Name = txtName.Text;
            entity.Email = txtEmail.Text;
            entity.Login = txtLogin.Text;
            entity.Password = txtPassword.Text;

            return entity;
        }

        protected override ExceptionsContainer _ValidateEntity(User entity)
        {
            ExceptionsContainer exs = new ExceptionsContainer();

			if (string.IsNullOrEmpty(entity.Name))
				exs.Add(new ValidationError("InvalidName", "O nome é de preenchimento obrigatório."));
			if (string.IsNullOrEmpty(entity.Login))
				exs.Add(new ValidationError("InvalidLogin", "O login é de preenchimento obrigatório."));
			if (string.IsNullOrEmpty(entity.Password))
				exs.Add(new ValidationError("InvalidPassword", "A senha é de preenchimento obrigatório."));
			else if (entity.Password.Length < 6)
				exs.Add(new ValidationError("InvalidPassword", "A senha deve ter pelo menos 6 caracteres."));
			else if (txtPassword.Text != txtConfirmPassword.Text)
				exs.Add(new ValidationError("PasswordMismatch", "O campo senha não confere."));

            return exs;
        }

        protected override int _SaveEntity(User entity)
        {
            ISecurityServicesProvider secProv = _Manager.ServicesProvider.CreateSecurityServicesProvider();

            int id = entity.Id;

            if (entity.Id > 0)
                secProv.UpdateUser(entity);
            else
                id = secProv.InsertUser(entity);

            return id;
        }  
        #endregion
        #endregion
	}
}
